import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);

const routes = [
  { path: '/', redirect: '/home' },
  //访问后台时，自动加载上“用户子组件”
  {
    path: '/home',
    name: 'home',
    component: () => import(/* webpackChunkName: "home" */ '@/views/home.vue'),
    redirect: '/repoList',
    children: [
      {
        path: '/repoList',
        name: '仓库列表',
        icon: 'el-icon-files',
        component: () =>
          import(
            /* webpackChunkName: "customer" */
            '@/components/repoList.vue'
          ),
      },

      {
        path: '/filterList',
        name: '过滤规则',
        icon: 'el-icon-set-up',
        component: () =>
          import(
            /* webpackChunkName: "manager" */ '@/components/filterList.vue'
          ),
      },
      {
        path: '/codeCountList',
        name: '历史数据',
        icon: 'el-icon-takeaway-box',
        component: () =>
          import(
            /* webpackChunkName: "manager" */ '@/components/codeCountList.vue'
          ),
      },
      {
        path: '/codeCountListSummary',
        name: '数据汇总',
        icon: 'el-icon-data-board',
        component: () =>
          import(
            /* webpackChunkName: "manager" */ '@/components/codeCountSummary.vue'
          ),
      },
      {
        path: '/email',
        name: '邮件预览',
        icon: 'el-icon-message',
        component: () =>
          import(
            /* webpackChunkName: "sendEmail" */ '@/components/sendEmail.vue'
          ),
      },
    ],
  },
];

const router = new VueRouter({
  mode: 'hash',
  routes,
  base: '/admin/',
});

//挂载路由导航守卫
// router.beforeEach((to, from, next) => {
//   //如果访问登录页，直接放行
//   if (to.path == '/login') return next();
//   //访问的不是登录页，查看是否有token,没有返回登录页
//   // const tokenStr = window.sessionStorage.getItem('token');
//   const tokenStr = localStorage.getItem('ticket');
//   if (!tokenStr) {
//     console.log('尚未登陆，自动跳转回首页');
//     return next({ path: '/login', query: to.query });
//   }
//   next();
// });

//new
router.beforeEach((to, from, next) => {
  const localTicket = localStorage.getItem('ticket');

  if (!localTicket) {
    const url = new URL(location.href);
    const urlTicket = url.searchParams.get('ticket');
    if (urlTicket) {
      localStorage.setItem('ticket', urlTicket);
      return next();
    }
    // console.log(2222, "sso");
    location.href = `${process.env.VUE_APP_LOGIN_HOST}/login?clientUrl=${window.location.href}`;
  }
  next();
});

export default router;
